#!/usr/bin/env python
import json
import datetime
import matplotlib.pyplot as plt
import time
import qb_database
import config
from collections import OrderedDict
from pylab import *



def dic_make(list_name,dict_name):
    '''make dict to list

    :param list_name:[[key,int],...] list must have key and value like [['shot1',20],['shot2',30],['shot1',40]]
    :param dict_name: just a name to return
    :return: {'shot1':60,'shot2':30}
    '''
    for i in list_name :
        if not dict_name.has_key(i[0]):
            dict_name[i[0]] = 0
        dict_name[i[0]] += i[1]
    return dict_name


def sort_key(old_dict, reverse = False):
    keys = sorted(old_dict.keys(),reverse=reverse)
    new_dict = OrderedDict()
    for key in keys:
        new_dict[key] = old_dict[key]
    return new_dict


def get_the_subjob_week(timestart_qube_sta, timestart_qube_end):
    """
    The number of subjob and complete subjob
    :param timestart_qube_sta: submit_time like '2019-01-10 15:00:00'
    :param timestart_qube_end: end_time
    :return:
    """
    list_per_subjob = []
    list_per_subjob_complete = []
    list_per_subjob_fail = []
    list_per_subjob_dict = {}
    list_per_subjob_complete_dict = {}
    list_per_subjob_fail_dict = {}
    all_subjob = 0
    all_complete = 0
    fail = 0
    q = qb_database.QubeDatabase()
    job = q.job(
        query_field='id,prod_show,prod_shot,prod_seq,status,timesubmit,timestart,timeout,timecomplete,todo,todotally,name',
        query='(status != 261) and (status != 48) and (timesubmit between %s and %s) and (prod_show = "ANBO")' % (
            timestart_qube_sta, timestart_qube_end))
    # job_len = len(job)
    for i in job:
        todotally = map(int, i['todotally'].split())
        all_subjob += int(i['todo'])
        timesubmit = time.strftime('%Y-%m-%d', time.localtime(i['timesubmit'] + config.QUBE_TIME))
        list_per_subjob.append([timesubmit, i['todo']])
        if i['status'] == 16:
            all_complete = todotally[2]
            list_per_subjob_complete.append([timesubmit, all_complete])
        if i['status'] == 32:
            fail = todotally[5]
            list_per_subjob_fail.append([timesubmit, fail])

    dic_make(list_per_subjob, list_per_subjob_dict)
    dic_make(list_per_subjob_complete, list_per_subjob_complete_dict)
    dic_make(list_per_subjob_fail,list_per_subjob_fail_dict)

    list_per_subjob_complete_dict = sort_key(list_per_subjob_complete_dict)
    list_per_subjob_dict = sort_key(list_per_subjob_dict)
    list_per_subjob_fail_dict = sort_key(list_per_subjob_fail_dict)

    return list_per_subjob_complete_dict, list_per_subjob_dict,list_per_subjob_fail_dict


def get_chart(data_complete, data_subjob, data_faile):
    index_x = []

    y_complete = []
    y_subjob = []
    y_fail = []
    for key,value in data_subjob.items():
        index_x.append(key)
        y_subjob.append(value)
    for i in index_x:
        if i in data_complete.keys():
            y_complete.append(data_complete[i])
        else:
            y_complete.append(0)
        if i in data_faile.keys():
            y_fail.append(data_faile[i])
        else:
            y_fail.append(0)

    fig = plt.figure()
    fig.set_size_inches(18, 12, forward=True)

    index = list(range(len(index_x)))
    plt.subplot2grid((2,1),(0,0),colspan=1)
    plt.plot(index, y_subjob, marker='.', ms=8, label=u'Subjob(sign)', color='green')
    plt.plot(index,y_complete,marker='.', ms=8, label=u'Complete', color='blue')
    plt.plot(index, y_fail, marker='.', ms=8, label=u'Complete', color='red')
    plt.xticks(index, [i[5:] for i in index_x], rotation=60)
    # plt.xlabel('Date')
    plt.ylabel('The number of frame')
    plt.grid(which='both')
    plt.legend(loc=0)
    for a,b in zip(index, y_subjob):
        plt.text(a,b+500, '%.0f'%b, ha='center', va='bottom', fontsize=10)

    # ======================bar==============================
    index = list(range(len(index_x)))
    bar_width = 0.2
    bar_1 = [i+bar_width for i in index]
    bar_2 = [i+bar_width for i in bar_1]
    # bar_3 = [i+bar_width for i in bar_2]

    # plt.figure(figsize=(20,8), dpi=80)
    plt.subplot2grid((2,1), (1, 0), colspan=1)
    plt.bar(index, y_subjob, width=bar_width, label=u'subjob', color='greenyellow', edgecolor='greenyellow', alpha=1)
    plt.bar(bar_1, y_complete, width=bar_width, label=u'complete(sign)',color='cornflowerblue', edgecolor='cornflowerblue', alpha=1)
    plt.bar(bar_2, y_fail, width=bar_width, label=u'faild', color='red', edgecolor='red', alpha=1)
    plt.xticks(bar_2, [i[5:] for i in index_x], rotation=60)
    plt.xlabel('Date')
    # plt.ylabel('The number of frame')
    plt.suptitle('The situations of subjob(%s--%s)'%(timestart[:-9], timeend[:-9]))
    plt.legend(loc=0)
    plt.grid(which='both')
    # # add text
    # for a,b in zip(index, y_subjob):
    #     plt.text(a+0.05,b+1, '%.0f'%b, ha='center', va='bottom', fontsize=8)
    for a, b in zip(bar_1, y_complete):
        plt.text(a+ 0.1, b + 1, '%.0f' % b, ha='center', va='bottom', fontsize=10)
    for a, b in zip(bar_2, y_fail):
        plt.text(a + 0.15, b + 1, '%.0f' % b, ha='center', va='bottom', fontsize=10)
    path2 = '/show/WDN/misc/dept/lgt/RenderFarm/archive/Classification_report/subjob_report/'
    plt.show()


if __name__ == "__main__":
    timeend = datetime.date.today() - datetime.timedelta(days=1)
    time_end_stamo = time.strptime(str(timeend) + ' 00:00:00', "%Y-%m-%d %H:%M:%S")
    timeend_default = time.strftime( "%Y-%m-%d %H:%M:%S",time_end_stamo)
    time_start = datetime.date.today() - datetime.timedelta(days=30)
    time_start_stamo = time.strptime(str(time_start) + ' 00:00:00', "%Y-%m-%d %H:%M:%S")
    timestart_default = time.strftime("%Y-%m-%d %H:%M:%S",time_start_stamo)

    timestart = raw_input('Plese input the Date of start (Exam:\033[22;36m %s \033[0m) :' % timestart_default)
    if timestart == '':
        timestart = timestart_default
        print '\033[22;36m %s \033[0m' % timestart
    timeend = raw_input('Plese input the Date of end (Exam:\033[22;36m %s \033[0m) :' % timeend_default)
    if timeend == '':
        timeend = timeend_default
        print '\033[22;36m %s \033[0m' % timeend

    timestart_arr_sta = time.strptime(timestart, "%Y-%m-%d %H:%M:%S")
    time_start_local = time.localtime(time.mktime(timestart_arr_sta))
    timestart_qube_sta = int(time.mktime(timestart_arr_sta)) - config.QUBE_TIME
    timestart_arr_end = time.strptime(timeend, "%Y-%m-%d %H:%M:%S")
    time_end_local = time.localtime(time.mktime(timestart_arr_end))
    timestart_qube_end = int(time.mktime(timestart_arr_end)) - config.QUBE_TIME
    data_complete, data_subjob, data_faile = get_the_subjob_week(timestart_qube_sta, timestart_qube_end)
    get_chart(data_complete, data_subjob, data_faile)